//
// Created by syj on 2024/3/14.
//

#ifndef TRANSMIDDLE_REMOTE_SINK_INL_H
#define TRANSMIDDLE_REMOTE_SINK_INL_H

#include <spdlog/sinks/syslog_sink.h>

//#include "middle/ipc/proxy.h"
//#include "middle/log/service/daemon_service.h"
#include "middle/log/service/log_config.h"
#include "middle/log/service/log_msg.h"

namespace log
{
    /*namespace {
        static const char *const kLoggerDaemon = "mv_loggerd";
        static std::atomic_bool is_daemon{false};
        static std::atomic_bool is_read{false};
        static std::shared_ptr<mos::ipc::Proxy<DaemonService>> proxy;
        static std::shared_ptr<spdlog::logger> sys_logger;
    }  // namespace*/

    /*template <typename Mutex>
    remote_sink<Mutex>::remote_sink(LogConfig const &config,
                                    std::promise<bool> &promise)
            : config_(config)
    {
        if (kLoggerDaemon == config_.id) {
            is_daemon.store(true);
            // sys_logger =
            //     spdlog::syslog_logger_mt(kLoggerDaemon, kLoggerDaemon, LOG_USER);
            return;
        }

        proxy =
                std::make_shared<mos::ipc::Proxy<DaemonService>>(DaemonService::loggerd);
        (*proxy)->close->On([this](auto const &event) {
            logger_->warn("{}", event);
            is_read.store(false);
        });

        auto handshake = [this, &promise] {
            if ((*proxy)->Handshake(config_).Get()) {
                logger_->debug("Handshake success");
                is_read.store(true);
            } else {
                logger_->error("Handshake failed");
            }
            promise.set_value(is_read.load());
        };
        proxy->ServiceFound->Then([this, handshake] {
            std::thread([this, handshake] {
                pthread_setname_np(pthread_self(), "hankshake");
                handshake();
            }).detach();
        });

        mos::Application::Instance()->Exiting->On([this] {
            Stop();

            if (is_read.load()) {
                is_read.store(false);
                (*proxy)->Quit(config_.id);
            }

            proxy.reset();
        });
    }*/

    /*template <typename Mutex>
    void remote_sink<Mutex>::sink_it_(const spdlog::details::log_msg &msg) {
        if (is_daemon.load()) {
            // sys_logger->log(msg.level, msg.payload);
            return;
        }

        if (!is_read.load()) return;
        if (!proxy) return;

        (*proxy)->Message(LogMsg(config_.id, msg));
    }
*/
    /*template <typename Mutex>
    void remote_sink<Mutex>::flush_() {
        if (is_daemon.load()) {
            // sys_logger->flush();
        }
    }*/

}//namespace log

#endif //TRANSMIDDLE_REMOTE_SINK_INL_H
